import Taro from "@tarojs/taro";
import { useEffect, useMemo, useState } from "react";
import { AppState, AppStateStatus, PermissionsAndroid } from "react-native";

const NAVIGATOR_HEIGHT = 44;
const TAB_BAR_HEIGHT = 60;

export const useSystemInfo = () => {
  return useMemo(() => {
    return Taro.getSystemInfoSync();
  }, []);
};

export const useStatusBarHeight = () => {
  if (process.env.TARO_ENV === "rn") {
    return require("react-native").StatusBar.currentHeight;
  }
  return Taro.getSystemInfoSync().statusBarHeight;
};


export const useWindowHeight = (showTabBar = true) => {
  const info = Taro.getSystemInfoSync();
  const { windowHeight, statusBarHeight = 0, screenHeight } = info;
  const tabBarHeight = showTabBar ? TAB_BAR_HEIGHT : 0;
  if (process.env.TARO_ENV === "rn") {
    return screenHeight - statusBarHeight - NAVIGATOR_HEIGHT - tabBarHeight;
  }

  if (process.env.TARO_ENV === "h5") {
    return windowHeight - tabBarHeight;
  }

  return windowHeight;
};

// 判断应用是否在前台
export const useIsForeground = (): boolean => {
  const [isForeground, setIsForeground] = useState(true);

  useEffect(() => {
    const onChange = (state: AppStateStatus): void => {
      setIsForeground(state === "active");
    };
    const listener = AppState.addEventListener("change", onChange);
    return () => listener.remove();
  }, [setIsForeground]);

  return isForeground;
};
